#ifndef CONFIG_MANAGER_H
#define CONFIG_MANAGER_H

#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <functional>
#include <json.hpp>
#include <mutex>

namespace ED {
namespace Base {

class ConfigManager {

    ConfigManager();
    ~ConfigManager();

public:
    static ConfigManager &GetInstance();

    bool LoadConfig(const std::string &filename);
    nlohmann::json GetConfig(const std::string &key);
    bool SetConfig(const std::string &key, const nlohmann::json &value);

    int32_t RegisterListener(const std::string &key, std::function<void(const nlohmann::json &)> listener);
    void UnregisterListener(const std::string &key, int listenerId);

private:
    void NotifyListeners(const std::string &key, const nlohmann::json &value);
    bool LoadConfigFromFile(const std::string &filename);
    bool SaveConfig(const std::string &filename);
    bool SaveConfigToFile(const std::string &filename);
    void BackupConfig(const std::string &filename);

private:
    std::mutex mutex_;
    nlohmann::json config_;
    std::map<std::string, std::map<int, std::function<void(const nlohmann::json &)>>> listeners_;
    int32_t nextListenerId_ = 0; // 用于生成唯一的监听者ID
    std::string filename_;
};

} // namespace Base
} // namespace ED

#endif // CONFIG_MANAGER_H
